//app.js
const commonRequst = require('/common/customRequst.js');
const commonUser = require('/common/commonUser.js');
App({
    //当小程序初始化完成时，会触发 onLaunch（全局只触发一次）。
    onLaunch: function () {
    
        this.globalData = {
            "workAipDomain": "192.168.3.125:8002",
            "access_token": '',
            "shareImage":'',
            "uploadFileObj":"",
            "Chat": {
                serviceConfig: {
                    "url": "192.168.3.125", //连接地址
                    "model": "user", //模型
                    "is_cross_domain": 1, //是否跨域
                    "wsport": "7272", //连接端口
                    "isWebScoket": false, //是否创建连接
                },
                //连接对象
                ws: {
                    socketTask: null,
                    Timer: null,
                    ErrorMsg: [], //发送失败的消息
                    MaxRetryCount: 3,
                    CurrentRetryCount: 0,
                    url: null,
                    ReConnection: true,
                },
                config: null,
                url: null,
                session_id: 0,
                bus_id: 0,
                msg_id: 0,
                session_info: null,
                chat_window: false,
                session_user: null,
                isTipsWarning: false,
                windowsobj: null,
                userLoginToken: null,
                init: function () {
                    let that = this;
                    //判断用户是否已经登录
                    that.ws.CurrentRetryCount = 0;
                    that.userLoginToken = commonUser.getUserToken();
                    if (that.userLoginToken == '' || that.userLoginToken == null) {
                        return;
                    };
                    //初始化连接配置文件
                    let initUrl = that.bindUrl('init');
                    commonRequst.getDomainRequest(initUrl, '').then(function (re) {
                        if (re.code == 1) {
                            //请求成功--赋值到配置中
                            that.config = re.data;
                            //连接webscoket
                            that.ws.url = that.bindUrl('wss');
                            if (!that.ws.socketTask || that.ws.socketTask.readyState == 3 || that.ws.socketTask.readyState == 2) {
                                that.connectSocket();
                            }
                            //判断是否有新消息
                            if (re.data.new_msg_num) {
                                if (typeof that.windowsobj.handleNewMessage === 'function') {
                                    that.windowsobj.handleNewMessage(re.data);
                                }
                            }
                        } else {
                            return;
                        }
                    }, function (res) {
                        return;
                    })
                },

                //连接WebSocket
                connectSocket() {
                    let that = this;
                    if (that.ws.url == null || that.ws.url == undefined || that.ws.url == '') {
                        return;
                    }
                    if (that.ws.CurrentRetryCount >= 3) {
                        return;
                    }
                    //创建链接
                    that.ws.socketTask = wx.connectSocket({
                        url: that.ws.url
                    });
                    //监听连接打开
                    that.ws.socketTask.onOpen(function (header, profile) {
                    
                        // 重新发送--失败的消息
                        if (that.ws.ErrorMsg.length > 0) {
                            for (let i in that.ws.ErrorMsg) {
                                that.sendMessage(JSON.parse(that.ws.ErrorMsg[i]));
                            }
                            that.ws.ErrorMsg = [];
                        }
                        //清理定时器
                        if (that.ws.Timer != null) {
                            clearInterval(that.ws.Timer);
                        }
                        //定时发送心跳
                        that.ws.Timer = setInterval(function () {
                            that.sendMessage();
                        }.bind(that), 28000);

                        that.serviceConfig.isWebScoket = true;

                    });

                    //监听接收到服务器消息
                    that.ws.socketTask.onMessage(function (evt) {
                        let data = JSON.parse(evt.data);
                        if (data.code == 0) {
                            wx.showToast({
                                title: data.msg,
                            })
                        };
                        that.handleMessage(data);
                    });

                    //监听断开连接
                    that.ws.socketTask.onClose(function (code, reason) {
                        console.log('连接已经断开');
                        if (that.ws.Timer != null) {
                            clearInterval(that.ws.Timer);
                        }
                        that.serviceConfig.isWebScoket = false;
                        if (that.ws.MaxRetryCount) {
                            //每3秒重新连接一次
                            that.ws.Timer = setInterval(function () {
                                that.retryWebSocket();
                            }.bind(that), 100);
                        }
                    });

                    //监听连接错误信息
                    that.ws.socketTask.onError(function (errMsg) {
                        console.log('服务已停止');
                        console.log(errMsg);
                        that.ws.CurrentRetryCount = 3;
                        that.ws.ReConnection = false;
                    });
                },
                //发送聊天消息
                sendMessage(message) {
                    let that = this;
                    if (!message) {
                        message = {
                            c: 'Message',
                            a: 'ping'
                        };
                    }
                    message = JSON.stringify(message);
                    if (that.ws.socketTask && that.ws.socketTask.readyState == 1) {
                        that.ws.socketTask.send({
                            data: message,
                            success: function (res) {},
                            fail: function (re) {
                                //消息发送失败--添加到消息失败队列中
                                that.ws.ErrorMsg.push(message);
                            }
                        });
                    } else {
                        that.ws.ErrorMsg.push(message);
                        that.retryWebSocket();
                    }
                },

                //处理服务器推送消息
                handleMessage(data) {
                    let that = this;
                    if(that.windowsobj){
                        if (typeof that.windowsobj.handleChatMag === 'function') {
                            that.windowsobj.handleChatMag(data);
                        }
                    }
                    
                },
                //重新连接
                retryWebSocket() {
                    let that = this;
                    if (that.ws.CurrentRetryCount < that.ws.MaxRetryCount) {
                        that.ws.CurrentRetryCount++;
                        that.connectSocket();
                    } else {
                        if (that.ws.Timer != null) {
                            clearInterval(that.ws.Timer);
                        }
                        if (that.ws.ReConnection) {
                            that.ws.Timer = setInterval(function () {
                                that.connectSocket();
                            }.bind(that), 10000);
                        }
                    }
                },
                //绑定请求url
                bindUrl: function (type) {
                    let that = this;
                    let url = null;
                    switch (type) {
                        case 'wss':
                            let token = '&token=' + that.config.token_list.fastchat_token;
                            url = 'wss://' + that.serviceConfig.url + ':' + that.serviceConfig.wsport + '?modulename=' + that.serviceConfig.model + token;
                            break;
                        case 'init':
                            url = "https://" + that.serviceConfig.url + '/index/index/initwebscoket?modulename=' + that.serviceConfig.model + '&user_token=' + that.userLoginToken;
                            break;
                        case 'upload':
                            url = "https://" + that.serviceConfig.url + '/index/upload/index?modulename=' + that.serviceConfig.model;
                            break;
                        case 'load_message_prompt':
                            url = "https://" + that.serviceConfig.url + '/index/common/load_message_prompt?modulename=' + that.serviceConfig.model;
                            break;
                    }
                    return url;
                }
            },
            "globalCateId": '',
            "imgSrc": ''  // 裁剪图片存放路径
        };
        //初始化WebSocket连接
        this.globalData.Chat.init();

    },
    //当小程序启动，或从后台进入前台显示，会触发 onShow
    onShow: function (option) {},

    scrollHeight: function (that) { // 获取页面高度，设置背景色，公用方法
        let windowHeight = wx.getSystemInfoSync().windowHeight; // 屏幕的高度
        let windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕的宽度
        return windowHeight * 750 / windowWidth
    }
});